package cz.proks.easyhelpdesk.gwt.activity;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.URL;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import cz.proks.easyhelpdesk.api.config.Configuration;
import cz.proks.easyhelpdesk.api.model.User;
import cz.proks.easyhelpdesk.gwt.ClientFactory;
import cz.proks.easyhelpdesk.gwt.Globals;
import cz.proks.easyhelpdesk.gwt.activity.base.BaseActivity;
import cz.proks.easyhelpdesk.gwt.place.HelpdesksPlace;
import cz.proks.easyhelpdesk.gwt.place.WelcomePlace;
import cz.proks.easyhelpdesk.gwt.ui.WelcomeView;
import cz.proks.easyhelpdesk.gwt.ui.WelcomeView.Presenter;
import cz.proks.easyhelpdesk.utils.UrlUtils;

public class WelcomeActivity extends BaseActivity<WelcomePlace> implements Presenter {
    private WelcomeView view;
    
    public WelcomeActivity(WelcomePlace place, ClientFactory clientFactory, PlaceHistoryMapper placeMapper) {
        super(place, clientFactory, placeMapper);
        view = getClientFactory().getWelcomeView();
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        User user = Globals.getCurrentUser();

        if (user != null)
            goTo(new HelpdesksPlace());
        else {            
            view.setPresenter(this);
            panel.setWidget(view);
        }
    }

    @Override
    public void goTo(Place place) {
        getClientFactory().getPlaceController().goTo(place);
    }

    @Override
    public String getAuthorizationUrl() {
        String authorizationUrl = UrlUtils.getGoogleOAuthUrl(Configuration.GWT.GOOGLE_OAUTH.CLIENT_ID, "code", new String[] {
                encodeUrl(Configuration.GWT.GOOGLE_OAUTH.GOOGLE_USER_INFO_SCOPE), encodeUrl(Configuration.GWT.GOOGLE_OAUTH.GOOGLE_EMAIL_SCOPE) },
                Configuration.GWT.OAUTH2_REDIRECT_URI, "online", URL.encodeQueryString(Configuration.GWT.GWT_OAUTH2_ENTRY));
        return authorizationUrl;        
    }

    private String encodeUrl(String url) {
        return URL.encode(url);
    }
}
